package br.ita.comp.ces22.quiz.core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionManager {
	private static ConnectionManager instance = null;
	private static Connection connection = null;
	private static String connectionUrl;
	
	static {
		try {
			Class.forName(PropertiesLoader.getField("driver"));
		} catch (ClassNotFoundException ex) {
			ObserverManager.notifyObservers(ex);
		}
	}

	private void setConnectionUrl(){
		connectionUrl =  "jdbc:"+ PropertiesLoader.getField("sgbd")+"://"+
		PropertiesLoader.getField("host")+":"+
		PropertiesLoader.getField("port")+"/" + 
		PropertiesLoader.getField("database");
	}
	
	private ConnectionManager(){
		setConnectionUrl();
	}

	public static ConnectionManager getInstance() {
		if (instance == null) {
			instance = new ConnectionManager();
		}
		return instance;
	}

	public Connection openConnection(){
		try {
			if (connection == null) {
				connection = DriverManager.getConnection(connectionUrl,
						PropertiesLoader.getField("user"), PropertiesLoader.getField("password"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

	public void closeConnection(){
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
